package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.User;
import com.tianxin.workbao.workBao.bean.UserDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.helper.GreenDaoHelper;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.SPUtils;
import com.tianxin.workbao.workBao.utils.common.StringUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.WhereCondition;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

/**
 * Created by hacker on 2017/6/19.
 */
public class UserDataProvide extends BaseDataProvide {
    private List<User> users;
    private Integer orgid;
    private int isFromServer;
    private UpdateListViewListener mUpdateListViewListener;
    private Handler mSaveDbHandler;
    private int mPage;
    private UserDao userDao;
    private boolean isGetData = true;

    public UserDataProvide(Context context, UpdateListViewListener listener) {
        super(context);
        this.mUpdateListViewListener = listener;
        userDao = GreenDaoHelper.newInstance().getDaoSession().getUserDao();
        mSaveDbHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(msg.obj.toString());
                    String resData = jsonObject.getString("data");
                    if (resData.startsWith("[") && resData.endsWith("]") && resData.length() > 3) {
                        users.clear();
                        users = BeansUtil.userToBeans(resData);
                        refreshUI();
                        for (User user : users) {
                            userDao.insertOrReplace(user);
                        }
                    } else {
                        User user = BeansUtil.userToBean(resData);
                        users.clear();
                        users.add(user);
                        refreshUI();
                        userDao.insertOrReplace(user);
                    }
                } catch (JSONException e) {
                    Log.d(TAG, "handleMessage: " + e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    Log.d(TAG, "handleMessage: " + e.getMessage());
                    e.printStackTrace();
                }
                getUsersFromDb(orgid, 1);
            }
        };
    }

    public List<User> getUsers() {
        return users;
    }

    public void getUsersByOrganizationId(Integer orgId, int page) {
        getUsersFromDb(orgId, page);
    }

    private void getUsersFromDb(Integer orgId, int page) {
        this.orgid = orgId;
        mPage = page;
        Query query = userDao.queryBuilder()
                .where(new WhereCondition.StringCondition("PORGID = " + orgId + " group by _id "))
                .offset((page - 1) * Constant.USER_PAGE_SIZE)
                .limit(Constant.USER_PAGE_SIZE)
                .build();
        users = query.list();
        if (users.isEmpty()) {
            if (isFromServer == 0) {
                getUsersFromServer();
            } else {
                mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
            }
        }
        refreshUI();
    }

    /**
     * get user information from server
     */
    public void getUsersFromServer() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            mUpdateListViewListener.showProgress();
            isFromServer = 1;
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.post(CommonRequest.createPostRequest(URL.getUserUrl(), params), getDisposeDataHandle());
        }
    }

    /**
     * 真正处理返回数据
     *
     * @param responseObj
     */
    private void handleResponseObj(Object responseObj) {
        try {
            JSONObject jsonObject = new JSONObject(responseObj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                if (isGetData == false) {
                    mUpdateListViewListener.showMessage("ok");
                    return;
                }
                if (jsonObject.getJSONArray(Constant.RESPONSE_DATA) != null) {
                    // 保存到数据库中
                    Message message = Message.obtain();
                    message.arg1 = 1;
                    message.obj = responseObj;
                    mSaveDbHandler.sendMessage(message);
                } else {
                    mUpdateListViewListener.showMessage(jsonObject.getString(Constant.RESPONSE_INFO));
                }
            } else {
                if (isGetData == false) {
                    mUpdateListViewListener.showMessage("failure"+jsonObject.getString(Constant.RESPONSE_INFO));
                    return;
                }
                mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
            }
        } catch (JSONException e) {
            showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
            e.printStackTrace();
        }
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {

        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        }
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mUpdateListViewListener.hideProgress();
                    if (responseObj.equals(null)) {
                        mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_response));
                    } else {
                        handleResponseObj(responseObj);
                    }
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mUpdateListViewListener.hideProgress();
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }

    /**
     * mobile login
     *
     * @param userName
     * @param password
     */
    public void login(String userName, String password) {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            return;
        }
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.LOGIN_USER_NAME, userName);
        map.put(Constant.LOGIN_PASSWORD, password);
        RequestParams params = new RequestParams(map);
        String loginUrl = URL.getUserLoginUrl();
        final Request request = CommonRequest.createPostRequest(loginUrl, params);
        CommonOkHttpClient.post(request, new DisposeDataHandle(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject jsonObject = new JSONObject(responseObj.toString());
                    int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
                    if (status > 0) {
                        mUpdateListViewListener.onRefreshData(jsonObject.getJSONObject(Constant.RESPONSE_DATA));
                    } else {
                        mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.login_failure));
                    }
                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode()
                            + ":" + exception.getEmsg());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        }));

    }


    @Override
    public void refreshUI() {
        if (users != null && !users.isEmpty()) {
            if (mPage > 1) {
                mUpdateListViewListener.onLoadMoreData(users);
            } else {
                mUpdateListViewListener.onRefreshData(users);
            }
        }
    }

    public void search(String query) {
        if (users != null) {
            users.clear();
            mPage = 1;
        }
        String where = "";
        if (StringUtils.isNumber(query)) {
            where = "MOBILETEL like '%" + query + "%'";
        } else if (StringUtils.isHasChineseChar(query)) {
            where = "NAME like '%" + query + "%'";
        } else if (StringUtils.isLatter(query)) {
            where = "USERNAME like '%" + query + "%'";
        } else {
            mUpdateListViewListener.showMessage("输入有错！");
        }
        if (where.length() < 1) return;
        Query<User> userQuery = userDao.queryBuilder()
                .where(new WhereCondition.StringCondition(where))
                .orderAsc(UserDao.Properties.Name)
                .build();
        users = userQuery.list();
        refreshUI();
    }

    public void alertPassword(String oldPwd, String newPwd) {
        isGetData = false;
        String apptoken = SPUtils.getPrefString(Constant.CURRENT_USER_APPTOKEN, null);
        if (apptoken == null) {
            mUpdateListViewListener.showMessage("登陆状态出错，请退出重先登陆后再试");
            return;
        }
        if (oldPwd.equals(null) || newPwd.equals(null)) {
            mUpdateListViewListener.showMessage("输入有错");
            return;
        }
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("oldpwd", oldPwd);
            map.put("newpwd", newPwd);
            String url = URL.getAlertPwdUrl();
            RequestParams params = new RequestParams(map);
            Request postRequest = CommonRequest.createPostRequest(url, params);
            CommonOkHttpClient.post(postRequest, getDisposeDataHandle());
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }
}
